package com.inifitness.tenant.core.config.mp.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import com.inifitness.tenant.core.config.mp.service.EncryptService;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Base64编码组件
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2024-01-09 16:38
 */
@Log4j2
@Component
@ConditionalOnProperty(value = "mp.encrypt.type", havingValue = "base64")
@RequiredArgsConstructor
@Data
public class Base64EncryptService implements EncryptService {

  @Override
  public String encrypt(String content) {
    if (!StringUtils.hasLength(content)) {
      return null;
    }
    try {
      return Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8));
    } catch (Exception e) {
      throw new RuntimeException("数据加密失败!", e);
    }
  }

  @Override
  public String decrypt(String content) {
    if (!StringUtils.hasLength(content)) {
      return null;
    }
    try {
      byte[] bytes = Base64.getDecoder().decode(content);
      return new String(bytes, StandardCharsets.UTF_8);
    } catch (Exception e) {
      throw new RuntimeException("数据解密失败!", e);
    }
  }
}